<template>
  <el-drawer v-model="drawer.show" :="attrs" class="k-drawer">
    <template #header="{ titleId, titleClass }">
      <div :id="titleId" :class="titleClass">
        <slot v-if="slots.drawerHeader" name="drawerHeader"></slot>
        <span v-else>{{ title }}</span>
      </div>
    </template>

    <el-scrollbar v-loading="drawer.loading" class="k-drawer-scrollbar">
      <slot></slot>
    </el-scrollbar>

    <template #footer v-if="showFooter">
      <div style="flex: auto">
        <el-button
          @click="handleCancel"
          :type="btnCancelType"
          :disabled="btnCancelDisabled"
          :icon="btnCancelIcon"
        >
          {{ btnCancelText }}
        </el-button>
        <el-button
          :disabled="btnConfirmDisabled"
          :loading="drawer.btnLoading"
          :type="btnConfirmType"
          @click="handleConfirm"
          :icon="btnConfirmIcon"
        >
          {{ btnConfirmText }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="kDrawer">
//@ts-ignore
import debounce from 'lodash/debounce'
const drawer = reactive({
  show: false, //是否展示抽屉
  btnLoading: false, //是否展示确定loading
  loading: false, //是否展示loading
})
const attrs = useAttrs()
const slots = useSlots() // 获取插槽内容
withDefaults(
  defineProps<{
    title?: string //Drawer 的标题，也可通过具名 slot （见下表）传入
    btnConfirmText?: string //确定的按钮文字
    btnConfirmType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | '' //确定的按钮类型
    btnConfirmDisabled?: boolean //确定的按钮禁用
    btnConfirmIcon?: string //确定按钮图标
    btnCancelText?: string //取消的按钮文字
    btnCancelType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | '' //取消的按钮类型
    btnCancelDisabled?: boolean // 取消的按钮禁用
    btnCancelIcon?: string //取消按钮图标
    showFooter?: boolean //是否展示底部
  }>(),
  {
    title: '抽屉标题',
    btnConfirmText: '确定',
    btnConfirmType: 'primary',
    btnConfirmDisabled: false,
    btnConfirmIcon: '',
    btnCancelText: '取消',
    btnCancelType: '',
    btnCancelDisabled: false,
    btnCancelIcon: '',
    showFooter: true,
  },
)
const emit = defineEmits(['cancel', 'confirm'])

/**
 * 确定方法
 */
const handleConfirm = debounce(() => {
  emit('confirm')
}, 400)
/**
 * 取消方法
 */
const handleCancel = () => {
  emit('cancel')
  close() //关闭抽屉
}
/**
 * 打开抽屉方法
 */
const open = () => (drawer.show = true)
/**
 * 关闭抽屉方法
 */
const close = () => (drawer.show = false)
/**
 * 是否打开按钮loading
 * @param show
 */
const showBtnLoading = (show = false) => (drawer.btnLoading = show)
/**
 *
 * @param show
 */
const showLoading = (show = false) => (drawer.loading = show)

defineExpose({
  open,
  close,
  showBtnLoading,
  showLoading,
})
</script>
<style lang="scss">
.k-drawer {
  .el-drawer__body {
    padding: 0 !important;
  }
  &-scrollbar {
    padding: var(--el-drawer-padding-primary);
  }
}
</style>
